/*=============================================================================

  Library: HMPBundleFrame

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include <QStringList>
#include <QMutexLocker>
#include <QDebug>

#include "Bundle_p.h"
#include "BundleConstants.h"
#include "IServiceReference.h"
#include "ServiceReference_p.h"
#include "ServiceRegistration_p.h"

//----------------------------------------------------------------------------
IServiceReference::IServiceReference()
  : d_ptr(new ServiceReferencePrivate(0))
{

}

//----------------------------------------------------------------------------
IServiceReference::IServiceReference(const IServiceReference& ref)
  : d_ptr(ref.d_ptr)
{
  d_func()->ref.ref();
}

//----------------------------------------------------------------------------
IServiceReference::IServiceReference(ServiceRegistrationPrivate* reg)
  : d_ptr(new ServiceReferencePrivate(reg))
{

}

//----------------------------------------------------------------------------
IServiceReference::operator bool() const
{
  return getPlugin();
}

//----------------------------------------------------------------------------
IServiceReference& IServiceReference::operator=(int null)
{
  if (null == 0)
  {
    if (!d_func()->ref.deref())
      delete d_ptr;
    d_ptr = new ServiceReferencePrivate(0);
  }
  return *this;
}

//----------------------------------------------------------------------------
IServiceReference::~IServiceReference()
{
  if (!d_func()->ref.deref())
    delete d_ptr;
}

//----------------------------------------------------------------------------
QVariant IServiceReference::getProperty(const QString& key) const
{
  Q_D(const ServiceReference);

  QMutexLocker lock(&d->registration->propsLock);

  return d->registration->properties.value(key);
}

void *IServiceReference::getProperty(const std::string &key) const
{

    QString Qkey(key.data());
    QVariant qv = getProperty(Qkey);
    if(qv.isValid())
    {
        return (void *)0;
    }
    else
    {
        return qv.value<void *>();
    }

}

bool IServiceReference::containsProperty(const std::string &key) const
{

    QString Qkey(key.data());
    QVariant var = getProperty(Qkey);
    if(var.isValid())
        return true;
    else
        return false;
}

//----------------------------------------------------------------------------
QStringList IServiceReference::qt_getPropertyKeys() const
{
  Q_D(const ServiceReference);

  QMutexLocker lock(&d->registration->propsLock);

  return d->registration->properties.keys();
}


std::list<std::string> IServiceReference::getPropertyKeys() const
{
    std::list<std::string> strList_std;

    QStringList strList_q = qt_getPropertyKeys();

    QStringList::iterator itr = strList_q.begin();
    for(; itr != strList_q.end();itr++)
    {
        strList_std.push_back( (*itr).toStdString() );
    }

    return strList_std;
}

//----------------------------------------------------------------------------
QSharedPointer<IBundle> IServiceReference::getPlugin() const
{
  if (d_func()->registration == 0 || d_func()->registration->plugin == 0)
  {
    return QSharedPointer<IBundle>();
  }

  return d_func()->registration->plugin->q_func().toStrongRef();
}

IBundle *IServiceReference::getBundle() const
{
    if (d_func()->registration == 0 || d_func()->registration->plugin == 0)
    {
      return NULL;
    }

    return d_func()->registration->plugin->q_func().toStrongRef().data();

}

//----------------------------------------------------------------------------
QList<QSharedPointer<IBundle> > IServiceReference::getUsingPlugins() const
{
  Q_D(const ServiceReference);

  QMutexLocker lock(&d->registration->propsLock);

  return d->registration->dependents.keys();
}

void IServiceReference::getUsingBundles(std::vector<IBundle *> &bundles) const
{
   QList<QSharedPointer<IBundle> > listBund =  getUsingPlugins();

   QList<QSharedPointer<IBundle> >::Iterator it = listBund.begin();

   for(; it != listBund.end(); it++)
   {
      IBundle *pt = (*it).data();
      bundles.push_back(pt);
   }

}

//----------------------------------------------------------------------------
bool IServiceReference::operator<(const IServiceReference& reference) const
{
  bool sameFw = d_func()->registration->plugin->fwCtx == reference.d_func()->registration->plugin->fwCtx;
  if (!sameFw)
  {
    throw InvalidArgumentException("Can not compare service references "
                                      "belonging to different framework "
                                      "instances.");
  }

  int r1 = getProperty(BundleConstants::SERVICE_RANKING).toInt();
  int r2 = reference.getProperty(BundleConstants::SERVICE_RANKING).toInt();

  if (r1 != r2)
  {
    // use ranking if ranking differs
    return r1 < r2;
  }
  else
  {
    qlonglong id1 = getProperty(BundleConstants::SERVICE_ID).toLongLong();
    qlonglong id2 = reference.getProperty(BundleConstants::SERVICE_ID).toLongLong();

    // otherwise compare using IDs,
    // is less than if it has a higher ID.
    return id2< id1;
  }
}

//----------------------------------------------------------------------------
bool IServiceReference::operator==(const IServiceReference& reference) const
{
  return d_func()->registration == reference.d_func()->registration;
}

//----------------------------------------------------------------------------
IServiceReference& IServiceReference::operator=(const IServiceReference& reference)
{
  ServiceReferencePrivate* curr_d = d_func();
  d_ptr = reference.d_ptr;
  d_ptr->ref.ref();

  if (!curr_d->ref.deref())
    delete curr_d;

  return *this;
}

//----------------------------------------------------------------------------
uint qHash(const IServiceReference& serviceRef)
{
  return qHash(serviceRef.d_func()->registration);
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug dbg, const IServiceReference& serviceRef)
{
  dbg.nospace() << "Reference for service object registered from "
      << serviceRef.getPlugin()->qt_getSymbolicName() << " " << serviceRef.getPlugin()->getVersion()
      << " (";
  int i = serviceRef.qt_getPropertyKeys().size();
  foreach(QString key, serviceRef.qt_getPropertyKeys())
  {
    dbg.nospace() << key << "=" << serviceRef.getProperty(key).toString();
    if (--i > 0) dbg.nospace() << ",";
  }
  dbg.nospace() << ")";

  return dbg.maybeSpace();
}
